<template>
  <div class="app-container client-stage">
    <el-radio-group class="state-radio-group" v-model="stateRadio" @change="changeModel">
      <el-radio-button label="列表视图" value="list" />
      <el-radio-button label="内容视图" value="content" />
    </el-radio-group>
    <template v-if="stateRadio === 'list'">
      <el-table
        :v-loading="isLoading"
        element-loading-text="数据加载中..."
        :data="stageList"
        stripe
        style="width: 100%"
        border
        :header-cell-style="{
          background: '#F2F6FC',
          color: '#909399',
          'font-weight': 400,
          'font-size': '14px'
        }"
        :row-class-name="tableRowClassName"
      >
        <el-table-column prop="stageName" label="客户阶段" show-overflow-tooltip fixed />
        <el-table-column prop="taskName" label="任务名称" show-overflow-tooltip fixed />
        <el-table-column prop="userName" label="责任人"></el-table-column>
        <el-table-column label="是否必须" width="100">
          <template #default="{ row }">
            <span>{{ row.isMust ? "是" : "否" }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="executeDays" label="标准天数" width="100"></el-table-column>
        <el-table-column label="状态" width="150">
          <template #default="{ row }">
            <el-tag :type="getStageState(row)[1]">{{ getStageState(row)[0] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="plainStartDate" label="计划开始日期" width="200"></el-table-column>
        <el-table-column prop="factStartDate" label="实际开始日期" width="200"></el-table-column>
        <el-table-column prop="plainEndDate" label="计划完成日期" width="200"></el-table-column>
        <el-table-column prop="factEndDate" label="实际完成日期" width="200"></el-table-column>
        <el-table-column label="操作" fixed="right" width="120">
          <template #default="{ row }">
            <el-space :gutter="10">
              <el-button v-if="showToDoButton(row).value" type="primary" link @click="handelStage(row)">办理</el-button>
              <el-button type="primary" link @click="handelCheckStage(row)">查看</el-button>
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </template>
    <!--  内容视图  start  -->
    <FormView v-else :customer-id="customerId" />
    <!--  内容视图  end  -->

    <!--  流程任务待办 start  -->
    <div class="client-stage-drawer">
      <el-drawer v-model="isShowProcessTask" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-intention">
          <title-view :title="taskInfo.taskName" />
          <div class="opt-instructions" ref="instructionsTitle">
            <el-icon><QuestionFilled /></el-icon>
            <span @click="handelShowInstructions(proxy)">操作说明</span>
            <Transition name="fade">
              <div class="instructions-container" ref="instructionsContainer" v-show="instructionsVisible">
                <div class="arrow"></div>
                <title-view title="操作说明" isClose @close="handelCloseInstructions" />
                <div class="editor-container" v-html="taskInfo.remark"></div>
              </div>
            </Transition>
          </div>
          <div class="state-forms" v-loading="formRenderLoading" element-loading-text="数据加载中...">
            <template v-if="formItemsData.length">
              <FormRender ref="formRenderRef" :forms="formItemsData" :config="formConfigData" v-model="formModelData" />
            </template>
            <template v-else>
              <el-empty />
            </template>
          </div>
          <!--start next-task-->
          <div
            class="next-task-content"
            v-if="!isDisableFollowUp"
            v-loading="isLoadingNextTask"
            element-loading-text="数据加载中..."
          >
            <NextTaskList v-model="nextTaskList"></NextTaskList>
          </div>
          <!--end next-task-->
          <div class="state-btns">
            <el-button style="width: 92px; background-color: #f2f3f5" @click="handelCloseForm" size="default">取消</el-button>
            <el-button
              style="width: 92px"
              v-if="!isDisableFollowUp && formItemsData.length"
              type="primary"
              @click="handelSubmitForm"
              :loading="isSubmitHandelLoading"
              :disabled="isUploadFile && !isGetUploadFileUrl"
              size="default"
              >确定</el-button
            >
          </div>
        </div>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <div class="tab-content">
            <CustomTabs v-model="currentCustomIndex" :tabList="referFollowTabs" @tab-change="changeTab" />
            <el-icon :size="20" @click="handelCloseForm">
              <Close />
            </el-icon>
          </div>

          <el-timeline
            v-if="currentCustomIndex === 0"
            style="max-width: 600px"
            :hollow="true"
            :class="{ 'hide-left-line': !followUpData.length }"
          >
            <el-timeline-item v-if="!isDisableFollowUp" type="primary">
              <div class="add-follow-up" @click="handleAddFollowUp">
                <el-icon>
                  <Plus />
                </el-icon>
                <span>添加跟进</span>
              </div>
            </el-timeline-item>
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData" type="primary">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followTime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
          <div v-if="currentCustomIndex === 1" class="task-forms" v-loading="isLoadingReference">
            <template v-if="referenceForms.length">
              <div class="task-forms__item" v-for="item in referenceForms">
                <div class="form-title">{{ item.processModel?.formName }}</div>
                <div class="form-render">
                  <FormRender :forms="item.processModel.formItems" :config="{}" v-model="item.data" />
                </div>
              </div>
            </template>
            <el-empty v-else />
          </div>
        </div>
      </el-drawer>
    </div>
    <!--  流程任务待办 end  -->

    <!-- 跟进任务待办 start-->
    <div class="client-follow-drawer">
      <el-drawer v-model="isFollowDrawer" :with-header="false" :close-on-click-modal="false" destroy-on-close>
        <div class="stage-follow-up" v-loading="isStateFollowLoading" element-loading-text="数据加载中...">
          <title-view title="跟进内容" isClose @close="handelCloseFollowDrawer" />
          <el-timeline style="max-width: 600px" :hollow="true" :class="{ 'hide-left-line': !followUpData.length }">
            <el-timeline-item v-if="!isDisableFollowUp" type="primary">
              <div class="add-follow-up" @click="handleAddFollowUp">
                <el-icon>
                  <Plus />
                </el-icon>
                <span>添加跟进</span>
              </div>
            </el-timeline-item>
            <template v-if="followUpData.length">
              <el-timeline-item v-for="item in followUpData" type="primary">
                <div class="timeline-date">
                  <span class="date">{{ followDate(item.trackDatetime).value }}</span>
                  <span class="time">
                    <el-icon><Clock /></el-icon>
                    {{ followtime(item.trackDatetime).value }}
                  </span>
                </div>
                <div>
                  <div class="timeline-title">{{ item.trackTypeName }}</div>
                  <div class="timeline-desc">
                    <div class="timeline-desc-content">
                      {{ item.contentDesc }}
                    </div>
                    <div class="timeline-desc-images">
                      <el-image
                        :preview-src-list="[imgItem.url]"
                        v-for="imgItem in item.crmFileVOList"
                        :key="imgItem.url"
                        :src="imgItem.url"
                      ></el-image>
                    </div>
                    <div class="timeline-desc-name">{{ item.roleName }}</div>
                  </div>
                </div>
              </el-timeline-item>
            </template>
            <el-empty v-else />
          </el-timeline>
          <!-- <div class="state-btns">
            <el-button @click="handelCloseFollowDrawer" size="default">取消</el-button>
          </div> -->
        </div>
      </el-drawer>
    </div>
    <!-- 跟进任务待办 end-->

    <!--  客户跟进 start  -->
    <follow-dialog v-if="isShowFollow" v-model="isShowFollow" :task-info="taskInfo" @submit-after="handleSubmitFollow" />
  </div>
</template>

<script setup>
import { ref, getCurrentInstance, nextTick, toRefs, watch } from "vue";
import { dayjs } from "element-plus";
import { Clock, Close, Plus, QuestionFilled } from "@element-plus/icons-vue";
import FormRender from "@/components/customComponents/formRender.vue";
import CustomTabs from "@/components/CustomTabs";
import NextTaskList from "@/components/NextTaskList";
import FormView from "./components/formView";
import FollowDialog from "@/components/followDialog";
import requestApis from "./apis";
import { stageStates, stageDeleteStates, referFollowTabs, taskStateFields } from "./config";
import { tableRowClassName } from "@/views/client/utils";
import { isHasFile, parseOrDefault } from "@/utils";
import defaultConfig from "@/settings";
import useComputedParams from "@/hooks/useComputedParams";
import useIsUploadFile from "@/hooks/useIsUploadFile";
import { useElementPosition } from "../../hooks/instructionsPosition";
import useUserStore from "@/store/modules/user";

const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});
const { proxy } = getCurrentInstance();
const userStore = useUserStore();

const stateRadio = ref("list");
const getStageState = item => {
  if (item.status === 4) {
    return stageDeleteStates.has(item.deleteType) ? stageDeleteStates.get(item.deleteType) : ["数据错误", "danger"];
  }
  return stageStates.has(item.status) ? stageStates.get(item.status) : ["数据错误", "danger"];
};
/**
 * 流程任务待办
 */
const isShowProcessTask = ref(false);
const isSubmitHandelLoading = ref(false);
const handelSubmitForm = async () => {
  await nextTick();
  proxy.$refs.formRenderRef.submitForm(async data => {
    if (!data) {
      return proxy.$modal.msgError("请完善信息");
    }
    try {
      isSubmitHandelLoading.value = true;
      const postData = {
        deptId: userStore.userInfo.mainDeptId,
        formData: formModelData.value,
        processUsers: {},
        nextTasks: nextTaskList.value
      };
      await requestApis.subStageViewContent(taskInfo.value.stageTaskId, postData);
      getStageListData();
      proxy.$modal.msgSuccess("提交成功");
      isSubmitHandelLoading.value = false;
      isShowProcessTask.value = false;
    } catch (err) {
      isSubmitHandelLoading.value = false;
    }
  });
};
const handelCloseForm = async () => {
  if (formItemsData.value?.length) {
    await nextTick();
    proxy.$refs.formRenderRef.resetForm(() => {
      formItemsData.value = [];
      formModelData.value = {};
    });
  }
  currentCustomIndex.value = 0;
  followUpData.value = [];
  instructionsVisible.value = false;
  isShowProcessTask.value = false;
};

/**
 * 跟进任务待办
 */
const isFollowDrawer = ref(false);
const handelCloseFollowDrawer = () => {
  isFollowDrawer.value = false;
  followUpData.value = [];
};

/**
 * 操作说明
 */
const {
  instructionsVisible,
  instructionsLeft,
  instructionsTop,
  arrowLeft,
  arrowTop,
  handelShowInstructions,
  handelCloseInstructions
} = useElementPosition();

/**
 * 客户阶段列表、内容视图
 */
const stageList = ref([]);
const isLoading = ref(false);
const getStageListData = async () => {
  try {
    isLoading.value = true;
    const { data = [] } = await requestApis.getStageList(props.customerId);
    const list = data?.length ? data : [];
    stageList.value = list.map(item => {
      return {
        ...item,
        // TODO：懒惰的后端
        plainStartDate: item.plainStartDate ? dayjs(item.plainStartDate).format("YYYY-MM-DD") : "",
        factStartDate: item.factStartDate ? dayjs(item.factStartDate).format("YYYY-MM-DD") : "",
        plainEndDate: item.plainEndDate ? dayjs(item.plainEndDate).format("YYYY-MM-DD") : "",
        factEndDate: item.factEndDate ? dayjs(item.factEndDate).format("YYYY-MM-DD") : ""
      };
    });
    isLoading.value = false;
  } catch (err) {
    isLoading.value = false;
  }
};
const showToDoButton = useComputedParams(row => {
  return ![taskStateFields.IN_REVIEW, taskStateFields.FINISHED].includes(row.status) && row.isOperate;
});

/**
 * 办理、查看
 */
const formRenderLoading = ref(false);
const isStateFollowLoading = ref(false);
const followUpData = ref([]);
const followUpTypes = ref([]);
const isDisableFollowUp = ref(false);
// 表单模型
const formConfigData = ref({}); // 表单配置
const formItemsData = ref([]); // 表单模型
const formModelData = ref({}); // 表单数据
// 是否有文件上传
// TODO: 没有考虑上传失败
const { isUploadFile, isGetUploadFileUrl } = toRefs(useIsUploadFile(formItemsData, formModelData));

// 表单模型数据
const getProcessModel = async requestProcessModel => {
  try {
    formRenderLoading.value = true;
    const { formId: defId, formInstanceId, customerId } = taskInfo.value;
    const { data = {} } = await requestProcessModel(defId, customerId);
    formItemsData.value = data?.formItems ? JSON.parse(data.formItems) : [];
    formConfigData.value = data?.formConfig ? JSON.parse(data.formConfig) : {};
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formInstanceId.value && getProcessInstanceForm();
    formRenderLoading.value = false;
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 表单模型——详情
const getAuditAndToDoData = async () => {
  try {
    formRenderLoading.value = true;
    const { formInstanceId } = taskInfo.value;
    const { data } = await requestApis.approvalForm(formInstanceId);
    formRenderLoading.value = false;
    formConfigData.value = data?.formConfig ?? {};
    formItemsData.value = isHasFile(data?.formItems ?? [], data?.formData ?? {});
    if (isDisableFollowUp.value) {
      formItemsData.value.forEach(item => {
        item.props.disabled = true;
      });
    }
    formModelData.value = data?.formData || {};
  } catch (err) {
    formRenderLoading.value = false;
  }
};
// 表单实例模型
const getProcessInstanceForm = async () => {
  const { formInstanceId } = taskInfo.value;
  const { data } = await requestApis.processInstanceForm(formInstanceId);
  formModelData.value = data ?? {};
};
// 跟进类型
const getFollowUpType = async () => {
  const { data = [] } = await requestApis.dictList({ dictType: defaultConfig.dicts.FOLLER_UP_TYPE });
  console.log(data, "<<<<<跟进类型");
  followUpTypes.value = data;
};
const getClientInfoAndFollow = customerId => {
  isStateFollowLoading.value = true;
  requestApis
    .clientInfoAndFollow(customerId)
    .then(res => {
      const crmCustomerTrackList = res.data?.crmCustomerTrackList || [];
      followUpData.value = crmCustomerTrackList.map(item => {
        item.roleName = `${item.roleName}  ${item.updateBy}提交于${item?.updateTime ? dayjs(item.updateTime).format("HH:mm") : ""}`;
        const followItem = followUpTypes.value.filter(subItem => subItem.dictCode === item.trackType);
        followItem && (item.trackTypeName = followItem.dictLabel);
        return item;
      });
      isStateFollowLoading.value = false;
    })
    .catch(err => {
      console.log("跟进详情>>>", err);
      isStateFollowLoading.value = false;
    });
};
const followDate = useComputedParams(time => {
  return dayjs(time).format("YYYY-MM-DD");
});
const followTime = useComputedParams(time => {
  return dayjs(time).format("hh:mm:ss");
});
// 切换视图
const changeModel = val => {
  val === "list" && getStageListData();
};

// 办理/客户跟进弹窗
const taskInfo = ref({});
const handelStage = data => {
  isDisableFollowUp.value = false;
  taskInfo.value = { ...data };
  getClientInfoAndFollow(data.customerId);
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    return;
  }
  isShowProcessTask.value = true;
  getProcessModel(requestApis.pendingProcessModel);
  getNextTaskList(data);
  currentCustomIndex.value === 1 && getPreviewFormsList();
};
// 查看/客户跟进弹窗
const handelCheckStage = data => {
  isDisableFollowUp.value = true;
  taskInfo.value = { ...data };
  getClientInfoAndFollow(data.customerId);
  if (data.taskType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK) {
    isFollowDrawer.value = true;
    return;
  }
  isShowProcessTask.value = true;
  data.formInstanceId && getAuditAndToDoData();
};

/**
 * 提交客户跟进
 */
const isShowFollow = ref(false);
const handleAddFollowUp = () => {
  isShowFollow.value = true;
};
const handleSubmitFollow = () => {
  const { customerId, currentType } = taskInfo.value;
  const isFollowTask = currentType === defaultConfig.taskTypeObj.FOLLOW_UP_TASK;
  isFollowTask && (isShowFollow.value = false);
  getClientInfoAndFollow(customerId);
  proxy.$modal.msgSuccess("操作成功");
};

/**
 * 下个任务
 * */
const isLoadingNextTask = ref(false);
const nextTaskList = ref([]);
const getNextTaskList = async taskData => {
  try {
    isLoadingNextTask.value = true;
    const { data } = await requestApis.toDoNextTask(taskData.stageTaskId);
    nextTaskList.value = data?.map(item => {
      return {
        ...item,
        plainStartDate: dayjs().format("YYYY-MM-DD")
      };
    });
    isLoadingNextTask.value = false;
  } catch (err) {
    isLoadingNextTask.value = false;
    console.log(err);
  }
};

/**
 * 任务参考
 */
const isLoadingReference = ref(false);
const referenceForms = ref([]);
const getPreviewFormsList = async () => {
  try {
    isLoadingReference.value = true;
    const { data } = await requestApis.previewFormsList(taskInfo.value.stageTaskId);
    referenceForms.value =
      data?.map(item => {
        const formItems = parseOrDefault(item.processModel?.formItems, []).map(item => {
          return {
            ...item,
            props: {
              ...item.props,
              disabled: true
            }
          };
        });
        return {
          processModel: {
            ...item.processModel,
            formItems
          },
          data: item.data ?? {}
        };
      }) || [];
    isLoadingReference.value = false;
  } catch (err) {
    isLoadingReference.value = false;
    console.log(err);
  }
};

/**
 * 切换跟进记录/任务参考
 */
const currentCustomIndex = ref(0);
const changeTab = index => {
  index === 0 && getClientInfoAndFollow(taskInfo.value.customerId);
  index === 1 && getPreviewFormsList();
};

getStageListData();
getFollowUpType();
</script>

<style scoped lang="scss">
@use "@/assets/styles/mixin";
@use "clientStage";
// 操作说明
.instructions-container {
  @include mixin.flex-column;
  overflow: auto;
  position: fixed;
  left: v-bind(instructionsLeft);
  top: v-bind(instructionsTop);
  z-index: 9999;
  width: 400px;
  height: 90vh;
  background: white;
  border-radius: 10px;
  padding: 20px;
  box-sizing: border-box;

  .arrow {
    position: fixed;
    left: v-bind(arrowLeft);
    top: v-bind(arrowTop);
    z-index: 9999;
    width: 0;
    height: 0;
    border: 14px solid transparent;
    border-left: 14px solid #fff;
  }
  .editor-container {
    flex: 1;
    width: 100%;
    overflow: auto;
  }
}
// 参考任务
.stage-follow-up {
  @include mixin.flex-column;
}
.task-forms {
  position: relative;
  flex: 1;
  overflow-y: auto;
  margin-top: 20px;
  :deep(.arco-empty) {
    @include mixin.position-center;
  }
  &__item {
    .form-title {
      margin-bottom: 5px;
      font-size: 14px;
      color: #3d3d3d;
      line-height: 22px;
    }
    .form-render {
      padding: 10px;
      background: #f6f8fa;
      border: 1px solid #dcdfe6;
    }
    & + .task-forms__item {
      margin-top: 20px;
    }
  }
  :deep(.el-empty) {
    @include mixin.position-center;
  }
  :deep(.form-item-el) {
    width: 100%;
  }
}
</style>
